var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
        }
    };
var courseSetting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "parentId",

            rootPId: -1
        },
        key: {
            url:"nourl",
        }
    },
    callback: {
        onClick: getTestList
    }
};
var ztree;
var courseTree;

function getTestList(event, treeId, treeNode){
    console.log(treeNode)
    $.ajax({
           url:baseURL +'sys/coursebody/getChapterIdAndSectionId',
           type:"POST",
            contentType: "application/json",
            data: JSON.stringify(treeNode),
           success:function () {
                }
        })
    vm.setCourseBody(treeNode)
    vm.reload()
}

function deleteCourseTest() {

    vm.deleteCourseTest2();
}

function update(item) {
    var id = item;
    if(id == null){
        return ;
    }
    vm.showList = false;
    vm.title = "修改";
    vm.getInfo(id);
}

function del(item) {
    var ids = item;
    if(ids == null){
        return ;
    }

    confirm('确定要删除选中的记录？', function() {
        $.ajax({
            type: "POST",
            url: baseURL + "myCourse/choosetest/delete",
            contentType: "application/json",
            data: JSON.stringify(ids),
            success: function (r) {
                if (r.code == 0) {
                    alert('操作成功');
                    vm.reload()

                } else {
                    alert(r.msg);
                }

            }
        });
    });
}


$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'myCourse/choosetest/list',
        datatype: "json",
        colModel: [
            { label: 'id', name: 'id', index: 'id', width: 20, key: true },
            { label: '类型', index: 'question_type_id',name:'questionTypeId', width: 40, formatter: function(value, options, row){
                    if(row.questionTypeId==0)
                        return '<span class="label label-info">判断题</span>'
                    else	if(row.questionTypeId==1)
                        return '<span class="label label-info">单选题</span>'
                    else	if(row.questionTypeId==2)
                        return '<span class="label label-info">多选题</span>'
                    else	if(row.questionTypeId==3)
                        return '<span class="label label-info">简答题</span>'
                    else
                        return '<span class="label label-info">没类型</span>'
                } },
            { label: '题干', name: 'questionContent', index: 'question_content', width: 80 },
            { label: '题干图片', name: 'questonContentImg', index: 'question_content', width: 80,
                formatter: function (data) {
                 if(data!=null)
                    return `<img src="${data}" style="height: 40px;width: 40px"></img>`;
                 else
                     return ""
                } },
            { label: '选项1', name: 'optionOne', index: 'option_one', width: 80 },
            { label: '选项1图片', name: 'optionOneImg', index: 'option_one_img', width: 80,
                formatter: function (data) {
                    if(data!=null)
                        return `<img src="${data}" style="height: 40px;width: 40px"></img>`;
                    else
                        return ""
                }  },
            { label: '选项2', name: 'optionTwo', index: 'option_two', width: 80 },
            { label: '选项2图片', name: 'optionTwoImg', index: 'option_two_img', width: 80 ,
                formatter: function (data) {
                    if(data!=null)
                        return `<img src="${data}" style="height: 40px;width: 40px"></img>`;
                    else
                        return ""
                } },
            { label: '选项3', name: 'optionThree', index: 'option_three', width: 80 },
            { label: '选项3图片', name: 'optionThreeImg', index: 'option_three_img', width: 80 ,
                formatter: function (data) {
                    if(data!=null)
                        return `<img src="${data}" style="height: 40px;width: 40px"></img>`;
                    else
                        return ""
                } },
            { label: '选项4', name: 'optionFour', index: 'option_four', width: 80 },
            { label: '选项4图片', name: 'optionFourImg', index: 'option_four_img', width: 80 ,
                formatter: function (data) {
                    if(data!=null)
                        return `<img src="${data}" style="height: 40px;width: 40px"></img>`;
                    else
                        return ""
                } },
            { label: '答案', name: 'answer', index: 'option_four', width: 80 },
            { label: '解析', name: 'analysis', index: 'answer', width: 80 },
            { label: '解析图片', name: 'analysisImg', index: 'option_one', width: 80,
                formatter: function (data) {
                    if(data!=null)
                        return `<img src="${data}" style="height: 40px;width: 40px"></img>`;
                    else
                        return ""
                }  },

            { label: '修改', name: 'id', index: 'answer', width: 80 ,

                formatter: function (data) {

                    return '<span class="label label-warning"  style="cursor:pointer;"  onclick="update('+data+')">修改</span>';

                }
            },

            { label: '删除', name: 'id', index: 'answer', width: 80 ,

                formatter: function (data) {

                    return '<span class="label label-warning" style="cursor:pointer;" onclick="del('+data+')">删除</span>';

                }
            }


        ],
        viewrecords: true,
        height: 385,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
    vm.getCourseTree();
    vm.getCourseTree2();
    new AjaxUpload('#upload', {
        action: baseURL + "course/courseTest/uploadTest",
        name: 'file',
        autoSubmit:true,
        responseType:"json",
        onSubmit:function(file, extension){
            if (!(extension && /^(xls|xlsx)$/.test(extension.toLowerCase()))){
                alert('只支持excel！');
                return false;
            }
        },
        onComplete : function(file, r){
            if(r.code == 0){
                $("#pic").attr('src',r.returnUrl);
                vm.course.coverPath=r.returnUrl
                vm.reload()
            }else{
                alert(r.msg);
            }
        }
    });

    new AjaxUpload('#uploadquestonContentImg', {
        action: baseURL + "course/teacher/upload",
        name: 'file',
        autoSubmit:true,
        responseType:"json",
        onSubmit:function(file, extension){
            if (!(extension && /^(jpg|jpeg|png|gif)$/.test(extension.toLowerCase()))){
                alert('只支持jpg、png、gif格式的图片！');
                return false;
            }
        },
        onComplete : function(file, r){
            if(r.code == 0){
                $("#questonContentImg").attr('src',r.returnUrl);
                vm.chooseTest.questonContentImg=r.returnUrl
            }else{
                alert(r.msg);
            }
        }
    });
    new AjaxUpload('#uploadoptionOneImg', {
        action: baseURL + "course/teacher/upload",
        name: 'file',
        autoSubmit:true,
        responseType:"json",
        onSubmit:function(file, extension){
            if (!(extension && /^(jpg|jpeg|png|gif)$/.test(extension.toLowerCase()))){
                alert('只支持jpg、png、gif格式的图片！');
                return false;
            }
        },
        onComplete : function(file, r){
            if(r.code == 0){
                $("#optionOneImg").attr('src',r.returnUrl);
                vm.chooseTest.optionOneImg=r.returnUrl
            }else{
                alert(r.msg);
            }
        }
    });
    new AjaxUpload('#uploadoptionTwoImg', {
        action: baseURL + "course/teacher/upload",
        name: 'file',
        autoSubmit:true,
        responseType:"json",
        onSubmit:function(file, extension){
            if (!(extension && /^(jpg|jpeg|png|gif)$/.test(extension.toLowerCase()))){
                alert('只支持jpg、png、gif格式的图片！');
                return false;
            }
        },
        onComplete : function(file, r){
            if(r.code == 0){
                $("#optionTwoImg").attr('src',r.returnUrl);
                vm.chooseTest.optionTwoImg=r.returnUrl
            }else{
                alert(r.msg);
            }
        }
    });
    new AjaxUpload('#uploadoptionThreeImg', {
        action: baseURL + "course/teacher/upload",
        name: 'file',
        autoSubmit:true,
        responseType:"json",
        onSubmit:function(file, extension){
            if (!(extension && /^(jpg|jpeg|png|gif)$/.test(extension.toLowerCase()))){
                alert('只支持jpg、png、gif格式的图片！');
                return false;
            }
        },
        onComplete : function(file, r){
            if(r.code == 0){
                $("#optionThreeImg").attr('src',r.returnUrl);
                vm.chooseTest.optionThreeImg=r.returnUrl
            }else{
                alert(r.msg);
            }
        }
    });
    new AjaxUpload('#uploadoptionFourImg', {
        action: baseURL + "course/teacher/upload",
        name: 'file',
        autoSubmit:true,
        responseType:"json",
        onSubmit:function(file, extension){
            if (!(extension && /^(jpg|jpeg|png|gif)$/.test(extension.toLowerCase()))){
                alert('只支持jpg、png、gif格式的图片！');
                return false;
            }
        },
        onComplete : function(file, r){
            if(r.code == 0){
                $("#optionFourImg").attr('src',r.returnUrl);
                vm.chooseTest.optionFourImg=r.returnUrl
            }else{
                alert(r.msg);
            }
        }
    });
    new AjaxUpload('#uploadanalysisImg', {
        action: baseURL + "course/teacher/upload",
        name: 'file',
        autoSubmit:true,
        responseType:"json",
        onSubmit:function(file, extension){
            if (!(extension && /^(jpg|jpeg|png|gif)$/.test(extension.toLowerCase()))){
                alert('只支持jpg、png、gif格式的图片！');
                return false;
            }
        },
        onComplete : function(file, r){
            if(r.code == 0){
                $("#analysisImg").attr('src',r.returnUrl);
                vm.chooseTest.analysisImg=r.returnUrl
            }else{
                alert(r.msg);
            }
        }
    });




});


var vm = new Vue({
	el:'#rrapp',
	data:{
		courseName:"",
        courseId:null,
		showList: true,
		title: null,
        searching:null,
        courseList:[],
        questionTypeIdd:null,
        lable1:true,
        lable2:true,
		courseBody: {
		    id:null,
            name:null
        },
        chooseTest:{},
		course:{
			id:null,
			name:"",
			allName:""
		},
        menu:{
            parentName:null,
            parentId:0,
            type:1,
            orderNum:0,
            couresID:0
        },
        menu2:{
            parentName:null,
            parentId:0,
            type:1,
            orderNum:0,
            couresID:0
        }
	},
	methods: {
	    check : function(questionTypeIdd){
	        if(questionTypeIdd == 0){
	            //判断
                vm.lable2=false;
            }else if(questionTypeIdd == 3){
	            //简答题
                vm.lable1=false;
                vm.lable2=false;
            }
        },
        setCourseBody:function(treeNode){
            vm.courseBody.id=treeNode.id
            vm.courseBody.name=treeNode.name
            vm.reload()
        },
        queryCourse:function () {
            vm.getCourseTree();
        },
        courseTree2: function(){
            vm.getCourseTree2();
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择菜单",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#cLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = courseTree.getSelectedNodes();
                    //选择上级部门
                    vm.courseBody.courseName = vm.courseName;
                    console.log(vm.courseBody.course_name);
                    vm.courseBody.parentId = node[0].id;
                    vm.courseBody.parentName = node[0].name;
                    layer.close(index);
                    }

            });
        },
        delquestonContentImg : function() {
            $.ajax({
                type:"POST",
                url: baseURL + "myCourse/choosetest/delquestonContentImg",
                data:JSON.stringify({
                    iid: vm.chooseTest.id,
                    typee:0
                }),
                contentType: "application/json",
                success :function (r) {
                    if(r.code ==0){
                        vm.getInfo(vm.chooseTest.id)
                        alert("删除当前图片成功")
                    }
                }
            })

        },
        deloptionOneImg : function() {
            $.ajax({
                type:"POST",
                url: baseURL + "myCourse/choosetest/delquestonContentImg",
                data:JSON.stringify({
                    iid: vm.chooseTest.id,
                    typee:1
                }),
                contentType: "application/json",
                success :function (r) {
                    if(r.code ==0){
                        vm.getInfo(vm.chooseTest.id)
                        alert("删除当前图片成功")
                    }
                }
            })

        },
        deloptionTwoImg : function() {
            $.ajax({
                type:"POST",
                url: baseURL + "myCourse/choosetest/delquestonContentImg",
                data:JSON.stringify({
                   iid: vm.chooseTest.id,
                    typee:2
                }),
                contentType: "application/json",
                success :function (r) {
                    if(r.code ==0){
                        vm.getInfo(vm.chooseTest.id)
                        alert("删除当前图片成功")
                    }
                }
            })

        },
        deloptionThreeImg : function() {
            $.ajax({
                type:"POST",
                url: baseURL + "myCourse/choosetest/delquestonContentImg",
                data:JSON.stringify({
                    iid: vm.chooseTest.id,
                    typee:3
                }),
                contentType: "application/json",
                success :function (r) {
                    if(r.code ==0){
                        vm.getInfo(vm.chooseTest.id)
                        alert("删除当前图片成功")
                    }
                }
            })

        },
        deloptionFourImg : function() {
            $.ajax({
                type:"POST",
                url: baseURL + "myCourse/choosetest/delquestonContentImg",
                data:JSON.stringify({
                    iid: vm.chooseTest.id,
                    typee:4
                }),
                contentType: "application/json",
                success :function (r) {
                    if(r.code ==0){
                        vm.getInfo(vm.chooseTest.id)
                        alert("删除当前图片成功")
                    }
                }
            })

        },
        delalayisImg : function() {
            $.ajax({
                type:"POST",
                url: baseURL + "myCourse/choosetest/delquestonContentImg",
                data:JSON.stringify({
                    iid: vm.chooseTest.id,
                    typee:5
                }),
                contentType: "application/json",
                success :function (r) {
                    if(r.code ==0){
                        vm.getInfo(vm.chooseTest.id)
                        alert("删除当前图片成功")
                    }
                }
            })

        },
        courseTree: function(){

            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择菜单",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    vm.getCourseTree();
                    var node = ztree.getSelectedNodes();
                    if(node[0].id<10000) {
                        //选择上级菜单
                        vm.courseName = node[0].id;
                        var colunms = CourseBody.initColumn();
                        var table = new TreeTable(CourseBody.id, baseURL + "sys/coursebody/courseList?courseName="+vm.id, colunms);
                        console.log(table)
                        table.setExpandColumn(2);
                        table.setIdField("id");
                        table.setCodeField("id");
                        table.setParentCodeField("parentId");
                        table.setExpandAll(false);
                        table.init();
                        CourseBody.table = table;
                        vm.getCourseTree();
                        layer.close(index);
                    }
                }
            });
        },
        getCourseTree: function(menuId){
            //加载菜单树
            $.get(baseURL + "/course/menu/select?searching="+vm.searching, function(r){
                vm.courseList=r.menuList
                console.log(vm.searching)
                console.log(r.menuList)
            })


        },
        deleteCourseTest2:function(){
            var msg = "您真的确定要删除本课程下测试题吗？\n\n请确认！";
            console.log(vm.searching)
            confirm(msg, function(){
                $.ajax({
                    type: "GET",
                    url: baseURL + "course/courseTest/deleteCourseTest?searching="+vm.course.id,
                    contentType: "application/json",
                    success: function(r){
                        if(r.code == 0){
                            alert('操作成功', function(index){
                                $("#jqGrid").trigger("reloadGrid");
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            });
        },
        exportCourseTest:function(){

            $('#export').attr('href','../../myCourse/myfile/export?courseId='+vm.course.id);
            document.getElementById("export").click()
            // $.ajax({
            //     type:"POST",
            //     url: baseURL + "myCourse/myfile/export",
            //     data:{
            //         courseId:vm.course.id,
            //     },
            //     contentType: "application/json",
            //     success:function () {
            //         alert("导出成功")
            //     }
            // })

        },
        getCourseTree2: function(){
            //加载部门树
            $.get(baseURL + "sys/coursebody/select?id="+vm.course.id, function(r){
                courseTree = $.fn.zTree.init($("#courseTree2"), courseSetting, r.deptList);

                var node = courseTree.getNodeByParam("id", vm.menu2.parentId);
                courseTree.selectNode(node);


            })
        },
		query: function () {
			vm.reload();
		},
		saveOrUpdate: function (event) {
			var url = vm.chooseTest.id == null ? "myCourse/choosetest/save" : "myCourse/choosetest/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json;charset=UTF-8;",
			    data: JSON.stringify(vm.chooseTest),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(index){
							vm.reload();
                         //   location. reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}

			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "myCourse/choosetest/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "myCourse/choosetest/info/"+id, function(r){
                $("#questonContentImg").attr('src',r.chooseTest.questonContentImg);
                $("#optionOneImg").attr('src',r.chooseTest.optionOneImg);
                $("#optionTwoImg").attr('src',r.chooseTest.optionTwoImg);
                $("#optionThreeImg").attr('src',r.chooseTest.optionThreeImg);
                $("#optionFourImg").attr('src',r.chooseTest.optionFourImg);
                $("#analysisImg").attr('src',r.chooseTest.analysisImg)
                vm.chooseTest = r.chooseTest;
                vm.questionTypeIdd = vm.chooseTest.questionTypeId;
                vm.check(vm.questionTypeIdd);
            });
		},
		reload: function (event) {
			vm.showList = true;
			vm.lable1=true;
			vm.lable2 = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{'courseBodyId': vm.courseBody.id},
                page:page
            }).trigger("reloadGrid");
            // CourseBody.table.refresh();
		}
		}

});

//选择多条记录
function getSelectedRows1() {
    var grid = $("#jqGrid");
    var rowKey = grid.getGridParam("selrow");
    if(!rowKey){
        alert("请选择一条记录");
        return ;
    }

    return grid.getGridParam("selarrrow");
}